package com.lyf.scm.admin.domain.service.impl;


import cn.hutool.core.date.DateUtil;
import com.github.pagehelper.PageInfo;
import com.lyf.scm.admin.api.dto.DirectlyExecuteDTO;
import com.lyf.scm.admin.api.dto.DirectlyExecuteInfoDTO;
import com.lyf.scm.admin.api.dto.PlanResponseDTO;
import com.lyf.scm.admin.domain.remote.allocationservice.facade.DirectlyExecuteFacade;
import com.lyf.scm.admin.domain.remote.item.facade.ItemCoreFacade;
import com.lyf.scm.admin.domain.service.DirectlyExecuteService;
import com.lyf.scm.admin.domain.util.BaseSearchUtil;
import com.lyf.scm.common.constants.CommonConstants;
import com.lyf.scm.common.enums.ExcelExportTypeEnum;
import com.lyf.scm.common.enums.ResponseMsg;
import com.lyf.scm.common.model.ExcelExportDTO;
import com.lyf.scm.common.model.SalesPlanSelectDTO;
import com.lyf.scm.common.util.date.MyDateUtil;
import com.rome.arch.core.exception.RomeException;
import com.rome.user.common.utils.UserContext;
import feign.Response;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * description:
 * 直营预测计划--执行
 *
 * @author: haodong
 * @data: 2020/8/5 13:31
 */
@Slf4j
@Service
public class DirectlyExecuteServiceImpl implements DirectlyExecuteService {

    @Resource
    private DirectlyExecuteFacade directlyExecuteFacade;

    @Resource
    private ItemCoreFacade itemCoreFacade;
    /**
     * 按条件查询直营预测计划
     *
     * @param directlyExecute
     * @return
     */
    @Override
    public PlanResponseDTO<List<DirectlyExecuteInfoDTO>> listBySelective(DirectlyExecuteDTO directlyExecute) {

        //获得最低级品类查询条件
        List<SalesPlanSelectDTO> categorySalesPlanSelect = itemCoreFacade.getSubcategoryCode(directlyExecute.getCategoryCodeList());
        //赋值品类搜索条件
        BaseSearchUtil.setSearchFields(directlyExecute, null, categorySalesPlanSelect, null);

        //根据开始时间获取间隔日期集合 默认14天
        List<Date> dateList = MyDateUtil.getDayDates(directlyExecute.getStartTime(), CommonConstants.DAY_SIZE - 1);
        directlyExecute.setDateList(dateList);
        directlyExecute.setStartTime(DateUtil.offsetDay(directlyExecute.getStartTime(), -1));
        directlyExecute.setEndTime(MyDateUtil.getLastDate(dateList, null));
        directlyExecute.setCreator(UserContext.getUserId());

        // 按条件查询直营预测计划
        PageInfo<DirectlyExecuteInfoDTO> pageInfo = directlyExecuteFacade.listBySelective(directlyExecute);
        //将格式处理为页面所需格式
        List<List<DirectlyExecuteInfoDTO>> directlyExeInfoLists = this.processingStructure(pageInfo.getList(),dateList);

        PlanResponseDTO<List<DirectlyExecuteInfoDTO>> planResponse = new PlanResponseDTO<>();
        planResponse.setInfoList(directlyExeInfoLists);
        planResponse.setTotal(pageInfo.getTotal());
        //格式化日期格式
        planResponse.setDateList(MyDateUtil.processDaysDate(dateList, "M.dd"));
        return planResponse;
    }


    /**
     * 查询全渠道直营预测计划
     *
     * @param directlyExecute
     * @return
     */
    @Override
    public PlanResponseDTO<DirectlyExecuteInfoDTO> listAllByDays(DirectlyExecuteDTO directlyExecute) {

        //获得最低级品类查询条件
        List<SalesPlanSelectDTO> categorySalesPlanSelect = itemCoreFacade.getSubcategoryCode(directlyExecute.getCategoryCodeList());
        //赋值品类搜索条件
        BaseSearchUtil.setSearchFields(directlyExecute, null, categorySalesPlanSelect, null);

        directlyExecute.setCreator(UserContext.getUserId());
        Date startTime = directlyExecute.getStartTime();
        Date endTime = directlyExecute.getEndTime();

        List<Date> dateList;
        if (null != endTime) {
            dateList = MyDateUtil.getDayDates(startTime, endTime);
            directlyExecute.setDateList(dateList);
            directlyExecute.setStartTime(DateUtil.offsetDay(directlyExecute.getStartTime(), -1));
        } else {
            //没有结束时间，默认14天
            dateList = MyDateUtil.getDayDates(startTime, CommonConstants.DAY_SIZE - 1);
            directlyExecute.setDateList(dateList);
            directlyExecute.setStartTime(DateUtil.offsetDay(directlyExecute.getStartTime(), -1));
            directlyExecute.setEndTime(MyDateUtil.getLastDate(dateList, null));
        }
        List<DirectlyExecuteInfoDTO> targetInfoList = directlyExecuteFacade.listAllByDays(directlyExecute);
        PlanResponseDTO<DirectlyExecuteInfoDTO> planResponse = new PlanResponseDTO<>();
        planResponse.setInfoList(targetInfoList);
        planResponse.setDateList(MyDateUtil.processDaysDate(dateList, "M.dd"));
        return planResponse;
    }


    /**
     * 导出Excel
     * @param excelExportDTO
     * @param type
     * @return
     */
    @Override
    public Response exportExcel(ExcelExportDTO excelExportDTO, Integer type) {
        if (type == null) {
            throw new RomeException(ResponseMsg.FAIL_2005.getCode(), ResponseMsg.FAIL_2005.getMsg());
        }
        DirectlyExecuteDTO directly = new DirectlyExecuteDTO();
        directly.setAreaCodeList(excelExportDTO.getAreaCodeList());
        directly.setCategoryCodeList(excelExportDTO.getCategoryCodeList());
        directly.setLayeredCodeList(excelExportDTO.getLayeredCodeList());
        directly.setCreator(UserContext.getUserId());
        //没有结束时间，默认14天
        List<Date> dateList = MyDateUtil.getDayDates(excelExportDTO.getStartTime(), CommonConstants.DAY_SIZE - 1);
        directly.setDateList(dateList);
        directly.setStartTime(DateUtil.offsetDay(excelExportDTO.getStartTime(), -1));
        directly.setEndTime(MyDateUtil.getLastDate(dateList, null));
        directly.setUnitType(excelExportDTO.getUnitType());
        //导出当页数据
        if (ExcelExportTypeEnum.CURRENT_PAGE_EXPORT.getType().equals(type)) {
            directly.setPageNum(excelExportDTO.getPageNum());
            directly.setPageSize(excelExportDTO.getPageSize());
        }
        //导出勾选
        if (ExcelExportTypeEnum.CHECKED_BOX_EXPORT.getType().equals(type)) {
            directly.setPageNum(excelExportDTO.getPageNum());
            directly.setPageSize(excelExportDTO.getPageSize());
            directly.setRowIndex(excelExportDTO.getRowIndex());
        }
        //获得最低级品类查询条件
        List<SalesPlanSelectDTO> categorySalesPlanSelect = itemCoreFacade.getSubcategoryCode(excelExportDTO.getCategoryCodeList());
        //赋值品类搜索条件
        BaseSearchUtil.setSearchFields(directly, null, categorySalesPlanSelect, null);

        //导出全部数据
        return directlyExecuteFacade.exportExcel(directly, type);
    }

    /**
     * 将格式处理为页面所需格式
     * @param infoList
     * @param dateList
     * @return
     */
    private List<List<DirectlyExecuteInfoDTO>> processingStructure(List<DirectlyExecuteInfoDTO> infoList, List<Date> dateList) {
        List<List<DirectlyExecuteInfoDTO>> directlyExeInfoLists = new ArrayList<>();
        if (CollectionUtils.isEmpty(infoList)){
            return directlyExeInfoLists;
        }
        infoList.forEach(item -> {
            List<DirectlyExecuteInfoDTO> directlyExeInfoList = new ArrayList<>();
            List<BigDecimal> historicalSalesAmount = item.getHistoricalSalesAmount();
            List<BigDecimal> forecastSalesAmount = item.getForecastSalesAmount();
            List<BigDecimal> actualDifference = item.getActualDifference();
            List<BigDecimal> actualDifferenceRate = item.getActualDifferenceRate();
            List<BigDecimal> forecastDifference = item.getForecastDifference();
            List<BigDecimal> forecastDifferenceRate = item.getForecastDifferenceRate();
            for (int i = 0; i < dateList.size(); i++) {
                DirectlyExecuteInfoDTO directlyExeInfo = new DirectlyExecuteInfoDTO();
                List<BigDecimal> historicalSalesAmountList = new ArrayList<>();
                List<BigDecimal> forecastSalesAmountList = new ArrayList<>();
                List<BigDecimal> actualDifferenceList = new ArrayList<>();
                List<BigDecimal> actualDifferenceRateList = new ArrayList<>();
                List<BigDecimal> forecastDifferenceList = new ArrayList<>();
                List<BigDecimal> forecastDifferenceRateList = new ArrayList<>();
                for (int j = 0; j < i; j++) {
                    historicalSalesAmountList.add(null);
                    forecastSalesAmountList.add(null);
                    actualDifferenceList.add(null);
                    actualDifferenceRateList.add(null);
                    forecastDifferenceList.add(null);
                    forecastDifferenceRateList.add(null);
                }
                for (int k = i; k < dateList.size(); k++) {
                    historicalSalesAmountList.add(historicalSalesAmount.get(k));
                    forecastSalesAmountList.add(forecastSalesAmount.get(k));
                    actualDifferenceList.add(actualDifference.get(k));
                    actualDifferenceRateList.add(actualDifferenceRate.get(k));
                    forecastDifferenceList.add(forecastDifference.get(k));
                    forecastDifferenceRateList.add(forecastDifferenceRate.get(k));
                }
                BeanUtils.copyProperties(item,directlyExeInfo);
                directlyExeInfo.setDay(DateUtil.format(dateList.get(i), "yyyy.MM.dd"));
                directlyExeInfo.setHistoricalSalesAmount(historicalSalesAmountList);
                directlyExeInfo.setForecastSalesAmount(forecastSalesAmountList);
                directlyExeInfo.setActualDifference(actualDifferenceList);
                directlyExeInfo.setActualDifferenceRate(actualDifferenceRateList);
                directlyExeInfo.setForecastDifference(forecastDifferenceList);
                directlyExeInfo.setForecastDifferenceRate(forecastDifferenceRateList);

                directlyExeInfoList.add(directlyExeInfo);
            }
            directlyExeInfoLists.add(directlyExeInfoList);
        });
        return directlyExeInfoLists;
    }
}
